<?php

namespace App\Http\Requests;

use App\Model\Operators;
use App\Model\Salesmen;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Factory;

class SalesmenRequest extends FormRequest
{

    /**
     * Determine if the user is authorized to make this request.
     *
     * @param Operators $operators
     * @param Salesmen $salesmen
     * @return bool
     */
    public function authorize(Operators $operators, Salesmen $salesmen)
    {
//        $user = $this->user();
//        if ($user->type != 2) {//当前用户不是运营商无权更改
//            return false;
//        }
//        if ($this->isMethod('put')) {
//            $id = reset($this->route()->parameters);
//            $s = $salesmen->find($id);
//            $o = $operators->find($s->operator_id);//不是当前上级运营商无权修改
//            if ($o->user_id != $user->id) {
//                return false;
//            }
//        }
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        $rules = [
            'name' => 'required|string',
            'phone' => [
                'required',
                'regex:/^1[34578][0-9]{9}$/',
                'unique:salesmen,phone,' . reset($this->route()->parameters)
            ],
            'id_card' => [
                'required',
                'regex:/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|[xX])$/'
            ],
//            'bank_card_no' => ['required', 'regex:/^([1-9]{1})(\d{14}|\d{18})$/'],
            'bank_card_name' => 'required',
            'bank_name' => 'required'
        ];
        if ($this->route()->getName() == 'salesmen.store') {
            $rules['phone'][] = 'unique:salesmen';
        }
        return $rules;
    }

    public function messages()
    {
        return [
            'required' => ':attribute是必填',
            'phone.regex' => '手机号不正确',
            'id_card.regex' => '身份证号不正确',
            'phone.unique' => '手机号被使用'
        ];
    }

    public function attributes()
    {
        return [
            'name' => '负责人姓名',
            'phone' => '负责人手机',
            'id_card' => '身份证号码',
            'bank_card_no' => '银行卡号',
            'bank_card_name' => '开户行',
            'bank_branch' => '支行'
        ];
    }
}
